package com.yyq.adms.usermanage.interceptor;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.yyq.adms.usermanage.bpo.SysOnlineUsersBpo;
import com.yyq.adms.usermanage.pojo.SysOnlineUsers;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;

public class UserInterceptor extends AbstractInterceptor {
	private static final long serialVersionUID = 971242140102542273L;
	/*private SysOnlineUsers onlineUsers;
	private SysOnlineUsersBpo OnlineBpo;
	
	@Resource(name="sysOnlineUsersBpo")
	public void setOnlineBpo(SysOnlineUsersBpo onlineBpo) {
		OnlineBpo = onlineBpo;
		OnlineBpo.setCls(onlineUsers.getClass());
		
	}*/



	@Override
	public String intercept(ActionInvocation Invocation) throws Exception {
		if (ServletActionContext.getRequest().getSession()==null) {
			//System.out.println("session 为空了！********************************************");
			return "noUser";
		}else {
			LoginUser user = (LoginUser) ServletActionContext.getRequest().getSession().getAttribute(Constants.LOGIN_USER);
			if (user==null) {
				String cmd = ServletActionContext.getRequest().getParameter("cmd");
				String creator = ServletActionContext.getRequest().getParameter("creator");
				/*if(("batchAdd".equals(cmd) || "upload".equals(cmd)) && creator != null && "(@#$%^&*!~)".equals(creator)){
					return Invocation.invoke();
				}*/
				return "noUser";
			}
			System.out.println("Interceptor before..........");
			WebApplicationContext wct = WebApplicationContextUtils.getWebApplicationContext(
					ServletActionContext.getServletContext());
			SysOnlineUsersBpo onlineBpo = wct.getBean("sysOnlineUsersBpo",SysOnlineUsersBpo.class);
			onlineBpo.setCls(SysOnlineUsers.class);
			SysOnlineUsers onlineUsers=(SysOnlineUsers) onlineBpo.findByPk(user.getUserId());
			System.out.println("Interceptor after..........");
			
/*			//生成环境用此处代码
			if(onlineUsers == null){  
				return "noUser";
			}
			if (onlineUsers!=null && !user.getIp().equals(onlineUsers.getIp())) {
				return "forcelogout"; 
			}
*/			
			//测试环境用此处代码
			if(onlineUsers == null && !"all".equals(user.getUserName())){  
				//System.out.println("在线用户为空*********************且不是all用户！");
				
				return "noUser";
			}
			if (onlineUsers!=null && !user.getIp().equals(onlineUsers.getIp())) {
				if(onlineUsers!=null && !"all".equals(onlineUsers.getUsername())){
					return "forcelogout";  
				}
			}
			
			return Invocation.invoke();
		}
	}

}
